import allure
import requests
from common.log.log import log
from time import sleep

class RequestHandler:
    def __init__(self, token, k, referer=None):
        """
        session管理器
        token：
        k：
        referer：管理台权限控制新增的请求头，必须带上才能进行鉴权
        """
        self.session = requests.session()
        if k == 'yg' or k == 'yc':
            """ 云购或云创小程序 """
            self.headers = {
                'Authori-zation': token,
                'content-type': 'application/json',
                'sign': '7384f2bef8762f108bedd32acb2495b5'
            }
        elif k == 'yk':
            """ 云客小程序 """
            self.headers = {
                'Authorization': token,
                'content-type': 'application/json'
            }
        elif k == 'yght':
            """ 云购或云创管理台 """
            self.headers = {
                'Authori-zation': token,
                'content-type': 'application/json',
                'Referer': referer
            }
        else:
            pass

    def visit(self, method, url, params=None, data=None, json=None, **kwargs):
        try:
            # log.info(f'请求method：{method}')
            log.info(f'请求url：{url}')
            # log.info(f'请求params：{params}')
            # log.info(f'请求data：{data}')
            # log.info(f'请求json：{json}')
            # log.info(f'请求headers：{self.headers}')
            response = self.session.request(method, url, params=params, data=data, json=json, headers=self.headers,
                                            verify=False,
                                            timeout=10,
                                            **kwargs)
            sleep(0.1)
            allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
            return response
        except Exception as e:
            log.error(f'API请求出现异常为：{e}')
            raise e

    def close_session(self):
        """关闭session"""
        self.session.close()


class YkRequestHandler(RequestHandler):
    def __init__(self, user_token, k):
        super(YkRequestHandler, self).__init__(user_token, k)

    def visit(self, method, url, params=None, data=None, json=None, **kwarg):
        res = super(YkRequestHandler, self).visit(method, url, params=params, data=data, json=json, **kwarg)
        return res


if __name__ == '__main__':
    # 以下是测试代码
    # post请求接口
    # url = 'https://hwyg.jinhua-global.com/jinhua/api/admin/store/retail/spread/userlist'
    # headers = {'Authori-zation': '392df00800474403aefe3bd152adea3b'}
    # payload = {"page": 1, "limit": 10, "dateLimit": "", "type": 0, "nickName": "", "uid": 236}
    # user_token = read_ini(BASE_DIR + '/config_yk.ini')['host']['userToken']
    user_token = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjgxMzA5MCwidU5hbWUiOiIxNTIxODcwMTg5NyIsInNjb3BlIjo4LCJleHAiOjE3NzQ0MjgyOTgsImlhdCI6MTY4ODAyODI5OH0.q_BrmIXoqtOPeCoYBAgnyTf0vXCecrkGju1KFNtIH0o'
    # url = 'https://jky.huawangglobal.com/apiserver/api/cart/count'
    url1 = 'https://jky.huawangglobal.com//apiserver/api/cart/num'
    # user_token = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjgxMzA5MCwidU5hbWUiOiIxNTIxODcwMTg5NyIsInNjb3BlIjo4LCJleHAiOjE3NzQ3NDczNTgsImlhdCI6MTY4ODM0NzM1OH0.UCepllKlzYD9hZWyuLjShS4lRpPM064wG6Lpe9k09aY'
    # headers = {'Authorization': user_token,'content-type':'application/json;charset=utf-8'}
    # payload = {"id": 2523, "number": 1}
    payload = {"id": 2591, "number": 2}

    # req = RequestHandler()
    # login_res = req.visit("post", url1, headers=headers,json=payload)
    # print(login_res.text)

    req = YkRequestHandler(user_token, 'yk')
    login = req.visit("post", url1, json=payload)
    print(login.text)
